/**
 * @file rlog.c
 *
 * @copyright This file creat by rensuiyi ,all right reserve!
 *
 * @author rensuyi
 *
 * @date 2013/12/21 11:20:50
 */

#include "rlog.h"
#include <stdarg.h>
#include <stdio.h>

//! @option  rlog buffer size
#ifndef RLOG_BUFFER_SIZE
#define RLOG_BUFFER_SIZE      (1024)
#endif /* RLOG_BUFFER_SIZE */

static char m_rlog_buffer[RLOG_BUFFER_SIZE];

struct st_rlog_describe {
  rlog_stream_t stream;
  uint8_t level;
};

static struct st_rlog_describe m_rlog =
{
  NULL,
  RLOG_INFO,
};

int rlog_init(rlog_stream_t stream, uint8_t level) {
  m_rlog.level = level;
  m_rlog.stream = stream;
  return 0;
}

uint8_t rlog_set_level(uint8_t level) {
  uint8_t previous = m_rlog.level;
  m_rlog.level = level;
  return previous;
}

uint8_t rlog_get_level(uint8_t level) {
  return m_rlog.level;
}

rlog_stream_t rlog_set_stream(rlog_stream_t stream) {
  rlog_stream_t preivous = m_rlog.stream;
  m_rlog.stream = stream;
  return preivous;
}

rlog_stream_t rlog_get_stream(void) {
  return m_rlog.stream;
}

void rlog(uint8_t level, char* fmt, ...) {
  va_list va_args;
  int len;

  // if the level lower,skip
  if (level < m_rlog.level) {
    return;
  }

  va_start(va_args, fmt);
  len = vsnprintf(m_rlog_buffer, RLOG_BUFFER_SIZE, fmt, va_args);
  va_end(va_args);

  if ((len != 0) && (m_rlog.stream != NULL)) {
    m_rlog.stream(m_rlog_buffer, len);
  }
}
